import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-12-02
 * Time:21:32
 */
class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private Long time;

    public MyTask (Runnable runnable ,int time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public Long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.getTime()-o.getTime());
    }

}
class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    private Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(()-> {
            while (true) {
                try {
                    synchronized (locker) {
                        MyTask task = queue.take();
                        if (task.getTime() <= System.currentTimeMillis()) {
                            task.getRunnable().run();
                        } else {
                            queue.put(task);
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable ,int timer) throws InterruptedException {
        MyTask myTask = new MyTask(runnable,timer);
        queue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }
}
public class Thread13 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1111111111111111111");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2222222222222222222");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("33333333333333333333");
            }
        },500);

    }
}
